package practise.sort.apacheSort;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import practise.sort.Person;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by richard on 5/5/14.
 */
public class ApacheSort {
    public static void main(String[] args){
        ApacheSort apacheSort = new ApacheSort();
        List<Person> persons = apacheSort.initPerson();

        Comparator<Person> nameComparator = ComparatorUtils.naturalComparator();
        Comparator<Person> ageCompator = ComparatorUtils.reversedComparator(ComparableComparator.getInstance());

        List<Object> sortFields = new ArrayList<Object>();
        sortFields.add(new BeanComparator("age",ageCompator));
        sortFields.add(new BeanComparator("name",nameComparator));

        ComparatorChain comparatorChain = new ComparatorChain(sortFields);
        apacheSort.print(persons);
        Collections.sort(persons,comparatorChain);
        apacheSort.print(persons);


    }

    public void print(List<Person> list){
        for(Person peson : list){
            System.out.println("age:"+peson.getAge()+"name:"+peson.getName());
        }
    }

    public List<Person> initPerson(){
        List<Person> persons = new ArrayList<Person>();
        persons.add(new Person(1,"1"));
        persons.add(new Person(5,"6"));
        persons.add(new Person(5,"5"));
        persons.add(new Person(2,"2"));
        return persons;
    }
}
